<script setup>
import { ref, watch } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";

import { getGatewayInfo, updateGatewayInfo } from "@/api/system";

const editable = ref(false)

const info = ref({
  name: "",
  id: "",
  position: "",
  version: "",
  watchEnable: false,
  watchIp: "",
  watchFreq: 60,
})
let infoSrc = ""

watch(editable, val => {
  if (!val) {
    info.value = JSON.parse(infoSrc)
  }
})

function toGetInfo() {
  getGatewayInfo().then(res => {
    if (res.code === 200) {
      info.value = res.data
      infoSrc = JSON.stringify(info.value)
    } else {
      ElMessage.error(res.msg)
    }
  }).catch(err => {
    console.log(err)
    ElMessage.error("网络异常，请稍后重试")
  })
}
toGetInfo()

function toUpdateInfo() {
  ElMessageBox.confirm("确认修改设备信息吗？", "提示", {
    type: "warning",
    confirmButtonText: "确定",
    cancelButtonText: "取消",
  }).then(() => {
    updateGatewayInfo(info.value).then(res => {
      if (res.code === 200) {
        ElMessage.success("修改成功")
        editable.value = false
        toGetInfo()
      } else {
        ElMessage.error(res.msg)
      }
    }).catch(err => {
      console.log(err)
      ElMessage.error("网络异常，请稍后重试")
    })
  }).catch(() => {})
}
</script>

<template>
  <el-card header="基础信息">
    <el-form>
      <el-form-item label="启用编辑">
        <el-switch v-model="editable" />
      </el-form-item>
      <el-form-item label="网关名称">
        <el-input class="form-item" :readonly="!editable" v-model="info.name"/>
      </el-form-item>
      <el-form-item label="唯一编号">
        <el-input class="form-item" :readonly="!editable" v-model="info.id" />
      </el-form-item>
      <el-form-item label="安装位置">
        <el-input class="form-item" :readonly="!editable" v-model="info.position" />
      </el-form-item>
      <el-form-item label="系统版本">
        {{ info.version }}
      </el-form-item>
      <el-form-item label="启用看门狗">
        <el-switch v-model="info.watchEnable" :disabled="!editable" />
      </el-form-item>
      <div v-if="info.watchEnable">
        <el-form-item label="检测目标">
          <el-input class="form-item" :readonly="!editable" v-model="info.watchIp"/>
        </el-form-item>
        <el-form-item label="检测频率">
          <el-input class="form-item" :readonly="!editable" v-model="info.watchFreq" type="number">
            <template #append>秒 / 次</template>
          </el-input>
        </el-form-item>
      </div>
      <el-form-item v-if="editable" label="">
        <el-button 
          :disabled="infoSrc === JSON.stringify(info)"
          type="primary" @click="toUpdateInfo()" 
          style="margin-left: 12px;"
        >确认修改</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<style lang="scss" scoped>
.form-item {
  width: 260px;
}
</style>
